var Role = function () {

    this.$grid_selector = $("#role-grid-table");
    this.pager_selector = "#role-grid-pager";

    this.URL = {
        MODULE_GET: '/member/module/role/{{id}}/ztree',
        ROLE_EDIT: '/member/role/{{id}}'
    };

    this.colModel = [
        {name: 'roleId', key: true, width: 50, editable: true},
        {
            name: 'name',
            width: 80,
            editable: true,
            editrules: {required: true, edithidden: true},
            editoptions: {
                size: "20", maxlength: "30"
            },
            formoptions: {}
        }, {
            name: 'code',
            width: 80,
            editable: true,
            editoptions: {size: "20", maxlength: "30"},
            editrules: {required: true}
        },
        {
            name: 'creator',
            editable: false
        },
        {
            name: 'status',
            width: 70,
            sortable: false,
            editable: true,
            edittype: "checkbox",
            editoptions: {value: "1:0", defaultValue: '1'},
            editrules: {required: true},
            formatter: function (cellValue) {
                if (cellValue === '1' || cellValue === 1)
                    return '开启';
                else
                    return '关闭';
            },
            unformat: function (cellValue) {
                if (cellValue === '开启')
                    return '1';
                else
                    return '0';
            }
        },
        {
            name: 'sequence',
            width: 50,
            editable: true,
            editoptions: {size: "20", maxlength: "30"},
            editrules: {required: true, number: true}
        },
        {
            name: 'comment',
            sortable: false,
            editable: true,
            edittype: "textarea",
            editrules: {required: true}
        }, {name: 'createdAt', width: 100}
    ];
    this.options = {
        moduleKey: 'member/role',
        pager: this.pager_selector,
        sortname: 'sequence',
        caption: "角色列表",
        colNames: ['角色ID', '名称', '编号', '创建者', '状态', '顺序', '说明', '创建时间'],
        colModel: this.colModel
    };
    this.permissionTemplate = '<div style="padding: 0 12px 0 12px;" ><ul id="role_permission_tree" class="ztree"></ul></div>';
};

Role.prototype = {
    // 初始化表格
    initGird: function () {

        var self = this;
        this.$grid_selector
            .xumf_jqGird(this.options)
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navSeparatorAdd', this.pager_selector)
        // 编辑权限按钮初始化
            .xumf_jqGird('navGrid', this.pager_selector).jqGrid('navButtonAdd', this.pager_selector,
            {
                caption: '',
                title: "设置权限",
                buttonicon: "fa fa-cog",
                onClickButton: function () {
                    $(this).getGridSelectedRow(function (rowData) {
                        self.permissionSetting(rowData);
                    });
                }
            });
    },
    permissionSetting: function (rowData) {

        var self = this;
        // 显示弹框
        layer.open({
            area: ['300px', '60%'],
            title: '权限配置',
            content: this.permissionTemplate,
            yes: function (index, layero) {
                self.permissionSettingAction(rowData, index);
            },
            success: function (index, layero) {
                var setting = {
                    check: {enable: true},
                    data: {simpleData: {enable: true}}
                };
                // 获取数据
                var url = _.template(self.URL.MODULE_GET)({ id: rowData.roleId });
                $.get(url).done(function (res) {
                    $.fn.zTree.init($('#role_permission_tree'), setting, res.data);
                });
            }
        });
    },
    /**
     * 修改角色权限动作
     * @param rowData 当前选择行
     * @param index layer当前层索引
     */
    permissionSettingAction: function (rowData, index) {
        var treeObj = $.fn.zTree.getZTreeObj("role_permission_tree");
        var nodes = treeObj.getCheckedNodes(true);
        // 获取权限id（后台返回数据中已-号区分，模块id与权限id）
        // 已选择的权限id
        var permissions = _.chain(nodes)
            .filter(function (item) {
                return item.id > 0
            })
            .pluck('id')
            .value()
            .join(',');
        $.xumf.ajaxAndLoading({
            type: 'PUT',
            url: _.template(this.URL.ROLE_EDIT)({id: rowData.roleId}),
            data: {roleId: rowData.roleId, permissions: permissions}
        }).success(function (res) {
            layer.close(index);
            $.xumf.gritter(res);
        });
    }
};

